package com.itheima.controller;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.WTTXRequest;
import com.itheima.pojo.WTTXResponse;
import com.itheima.util.IpUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;

/**
 * @author 刘志豪
 * @version 1.0
 * @description: TODO
 * @date 2021/8/18 16:14
 */
@Controller
@RequestMapping("/wttx")
public class WTTXController {
    private static final String url = "https://wxapp.lqfast.com/mpapi.ashx";

    private static final String head = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1 wechatdevtools/1.05.2107090 MicroMessenger/8.0.5 Language/zh_CN webview/";

    @GetMapping(value = "/getMapApi")
    @ResponseBody
    public Object getMapApi(HttpServletRequest request){
            String trackNo = request.getParameter("trackNo");
            String[] splits = trackNo.split("-");
            String response = null;
            if (splits != null && splits.length != 0){
                HashMap<String, Object> map = new HashMap<>();
                // 单号为65237-3250
                try {
                    WTTXRequest wttxRequest = new WTTXRequest();
                    wttxRequest.setMethod("QSP_TYD_WTTX");
                    wttxRequest.setQtype(splits[0]);
                    WTTXRequest.Par par = new WTTXRequest.Par();
                    par.setUnit(splits[1]);
                    wttxRequest.setPars(Arrays.asList(par));
                    System.out.println("request params-------------------------------"+JSONUtil.toJsonStr(wttxRequest));
                    map.put("data", JSONUtil.toJsonStr(wttxRequest));
                    response = HttpUtil.createGet(url).header("User-Agent", head).header("X-FORWARDED-FOR", IpUtil.getRandomIp()).form(map).execute().body();
                    WTTXResponse wttxResponse = JSON.parseObject(response, WTTXResponse.class);
                    return wttxResponse;

                } catch (HttpException e) {
                    e.printStackTrace();
                }
            }
            return response;

    }
}
